package com.the4man.cnbdw.action;

import com.opensymphony.xwork2.ModelDriven;
import com.the4man.cnbdw.service.*;
import com.the4man.cnbdw.utils.Page;
import com.the4man.cnbdw.utils.SplitImage;
import com.the4man.framework.action.BaseAction;
import com.the4man.framework.model.*;
import com.the4man.framework.model.gen.FenceInfoExampleBase;
import com.the4man.framework.util.DateUtil;
import com.the4man.framework.util.LOG;
import com.the4man.framework.util.PageJson;
import com.the4man.framework.utils.RequestUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

@Action(
        value = "smapInfoAction",
        results = {@Result(
                name = "addPage",
                location = "/cnbdw/smapInfo/add.jsp"
        ), @Result(
                name = "listPage",
                location = "/cnbdw/smapInfo/list.jsp"
        ), @Result(
                name = "showFencesPage",
                location = "/cnbdw/smapInfo/showFences.jsp"
        ), @Result(
                name = "showPanel",
                location = "/cnbdw/smapInfo/showPanel.jsp"
        ), @Result(
                name = "locationStateSet",
                location = "/cnbdw/smapInfo/locationStateSet.jsp"
        ), @Result(
                name = "showMonitorPage",
                location = "/cnbdw/smapInfo/monitor.jsp"
        ), @Result(
                name = "editPage",
                location = "/cnbdw/smapInfo/edit.jsp"
        )}
)
public class SmapInfoAction extends BaseAction implements ModelDriven<SmapInfo> {
    private static final String HEART_MIN = "heart_min";
    private static final String HEART_MAX = "heart_max";
    private SmapInfo smapInfo = new SmapInfo();
    private LogInfo logInfo = new LogInfo();
    @Autowired
    private LogInfoService logService;
    @Autowired
    private SmapInfoService smapInfoService;
    @Autowired
    private FenceInfoService fenceInfoService;
    @Autowired
    private PointInfoService pointInfoService;
    @Autowired
    private RegionInfoService regionInfoService;

    public SmapInfoAction() {
    }

    public String indexPage() {
        return "listPage";
    }

    public String toAddPage() {
        return "addPage";
    }

    public String toSetLocationState() {
        return "locationStateSet";
    }

    public String toEditPage() {
        try {
            SmapInfo smap = (SmapInfo)this.smapInfoService.selectByPrimaryKey(this.smapInfo.getId(), SmapInfo.class);
            BeanUtils.copyProperties(smap, this.getModel());
        } catch (Exception var2) {
            var2.printStackTrace();
        }

        return "editPage";
    }

    public void getAllDatasourceList() {
        try {
            SmapInfoExample smapInfoExample = new SmapInfoExample();
            this.smapInfoService.countByExample(smapInfoExample);
            Page<SmapInfo> page = new Page();
            this.smapInfoService.selectByExample(smapInfoExample, page);
            DataGrid d = new DataGrid();
            d.setRows(page.getData());
            d.setTotal(Long.valueOf((long)page.getRowCount()));
            this.writeJson(d);
        } catch (Exception var5) {
            LOG.error("获取数据失败", var5, new String[0]);
        }

    }

    public void getMapInfoSelectData() {
        try {
            SmapInfoExample smapInfoExample = new SmapInfoExample();
            smapInfoExample.createCriteria().andDeckIdEqualTo(this.getRequest().getParameter("deckId"));
            List list = this.smapInfoService.selectByExample(smapInfoExample);
            this.writeJson(list);
        } catch (Exception var3) {
            LOG.error("获取数据失败", var3, new String[0]);
        }

    }

    public void add() {
        PageJson json = new PageJson();

        try {
            SmapInfoExample smapInfoExample = new SmapInfoExample();
            smapInfoExample.createCriteria().andCodeEqualTo(this.smapInfo.getCode());
            List list = this.smapInfoService.selectByExample(smapInfoExample);
            if(list != null && !list.isEmpty()) {
                json.setReturnFlag(false);
                json.setReturnMsg("存在相同编号的地图");
                this.writeJson(json);
                return;
            }

            SmapInfoExample smapInfoExample1 = new SmapInfoExample();
            smapInfoExample1.createCriteria().andNameEqualTo(this.smapInfo.getName());
            List list1 = this.smapInfoService.selectByExample(smapInfoExample1);
            if(list1 != null && !list1.isEmpty()) {
                json.setReturnFlag(false);
                json.setReturnMsg("存在相同名称的地图");
                this.writeJson(json);
                return;
            }

            this.smapInfo.setId(UUID.randomUUID().toString());
            String time = DateUtil.getInstance().formatDate(new Date());
            this.smapInfo.setCreateTime(time);
            this.smapInfo.setUpdateTime(time);
            this.smapInfo.setCreateUser(RequestUtil.getSessionUserinfo().getUsername());
            this.smapInfo.setUpdateUser(RequestUtil.getSessionUserinfo().getUsername());
            this.smapInfoService.insert(this.smapInfo);
            this.logInfo.setId(UUID.randomUUID().toString());
            this.logInfo.setTime(time);
            this.logInfo.setUserName(RequestUtil.getSessionUserinfo().getUsername());
            this.logInfo.setUserId(RequestUtil.getSessionUserinfo().getUserid());
            this.logInfo.setFunc("地图管理");
            this.logInfo.setOp("地图添加");
            this.logInfo.setMemo("地图名:" + this.smapInfo.getName());
            this.logService.insert(this.logInfo);

            try {
                String basePath = this.getRequest().getRealPath("/");
                String realPath = basePath + File.separator + "smap" + File.separator + "gallery" + File.separator + this.smapInfo.getId() + File.separator;
                SplitImage.generateImage(basePath + this.smapInfo.getBgImage(), realPath, -1);
                System.out.println("generate images successful.");
            } catch (Exception var9) {
                var9.printStackTrace();
            }

            json.setReturnFlag(true);
            json.setReturnMsg("提交成功！");
        } catch (Exception var10) {
            json.setReturnFlag(false);
            json.setReturnMsg("提交出错了");
            LOG.error("获取数据失败", var10, new String[0]);
        }

        this.writeJson(json);
    }

    public void update() {
        PageJson json = new PageJson();

        try {
            Object o = this.smapInfoService.selectByPrimaryKey(this.smapInfo.getId(), SmapInfo.class);
            if(o == null) {
                json.setReturnFlag(false);
                json.setReturnMsg("修改的记录不存在");
                this.writeJson(json);
                return;
            }

            String smapc = this.smapInfo.getCode();
            String smapi = this.smapInfo.getId();
            SmapInfoExample smapInfoExample = new SmapInfoExample();
            smapInfoExample.createCriteria().andCodeEqualTo(this.smapInfo.getCode()).andIdNotEqualTo(this.smapInfo.getId());
            List list = this.smapInfoService.selectByExample(smapInfoExample);
            if(list != null && !list.isEmpty()) {
                json.setReturnFlag(false);
                json.setReturnMsg("存在相同编号的地图");
                this.writeJson(json);
                return;
            }

            SmapInfoExample smapInfoExample1 = new SmapInfoExample();
            smapInfoExample1.createCriteria().andNameEqualTo(this.smapInfo.getName()).andIdNotEqualTo(this.smapInfo.getId());
            List list1 = this.smapInfoService.selectByExample(smapInfoExample1);
            if(list1 != null && !list1.isEmpty()) {
                json.setReturnFlag(false);
                json.setReturnMsg("存在相同名称的地图");
                this.writeJson(json);
                return;
            }

            this.smapInfo.setUpdateTime(DateUtil.getInstance().formatDate(new Date()));
            this.smapInfo.setUpdateUser(RequestUtil.getSessionUserinfo().getUsername());
            SmapInfo smap = (SmapInfo)o;
            boolean changed = !StringUtils.equalsIgnoreCase(this.smapInfo.getBgImage(), smap.getBgImage());
            BeanUtils.copyProperties(this.smapInfo, o, new String[]{"createTime", "createUser"});
            this.smapInfoService.updateByPrimaryKey(o);
            this.logInfo.setId(UUID.randomUUID().toString());
            this.logInfo.setTime(DateUtil.getInstance().formatDate(new Date()));
            this.logInfo.setUserName(RequestUtil.getSessionUserinfo().getUsername());
            this.logInfo.setUserId(RequestUtil.getSessionUserinfo().getUserid());
            this.logInfo.setFunc("地图管理");
            this.logInfo.setOp("地图修改");
            this.logInfo.setMemo("地图名:" + this.smapInfo.getName());
            this.logService.insert(this.logInfo);
            if(changed) {
                try {
                    String basePath = this.getRequest().getRealPath("/");
                    String realPath = basePath + File.separator + "smap" + File.separator + "gallery" + File.separator + smap.getId() + File.separator;
                    SplitImage.generateImage(basePath + smap.getBgImage(), realPath, -1);
                    System.out.println("generate images successful.");
                } catch (Exception var13) {
                    var13.printStackTrace();
                }
            }

            json.setReturnFlag(true);
            json.setReturnMsg("提交成功！");
        } catch (Exception var14) {
            json.setReturnFlag(false);
            json.setReturnMsg("提交出错了");
            LOG.error("获取数据失败", var14, new String[0]);
        }

        this.writeJson(json);
    }

    public String executeModifyResult() {
        try {
            Object instance = this.smapInfoService.selectByPrimaryKey(this.smapInfo.getId(), SmapInfo.class);
            this.getRequest().setAttribute("instance", instance);
        } catch (Exception var2) {
            LOG.error("获取数据失败", var2, new String[0]);
        }

        return "modifyPage";
    }

    public void delete() {
        PageJson json = new PageJson();

        try {
            String ids = this.getRequest().getParameter("ids");
            int j = 0;
            String[] list = ids.split(",");

            for(int i = 0; i < list.length; ++i) {
                SmapInfo smap = (SmapInfo)this.smapInfoService.selectByPrimaryKey(list[i], SmapInfo.class);
                j = this.smapInfoService.deleteByPrimaryKey(list[i], SmapInfo.class);
                this.logInfo.setId(UUID.randomUUID().toString());
                this.logInfo.setTime(DateUtil.getInstance().formatDate(new Date()));
                this.logInfo.setUserName(RequestUtil.getSessionUserinfo().getUsername());
                this.logInfo.setUserId(RequestUtil.getSessionUserinfo().getUserid());
                this.logInfo.setFunc("地图管理");
                this.logInfo.setOp("地图删除");
                this.logInfo.setMemo("地图名:" + smap.getName());
                this.logService.insert(this.logInfo);
            }

            if(j > 0) {
                json.setReturnMsg("删除成功！");
                json.setReturnFlag(true);
            } else {
                json.setReturnMsg("删除失败！");
                json.setReturnFlag(false);
            }
        } catch (Exception var7) {
            LOG.error("批量删除失败！", var7, new String[0]);
            json.setReturnMsg("删除失败！");
            json.setReturnFlag(false);
        }

        this.writeJson(json);
    }

    public void verify() {
        PageJson json = new PageJson();
        this.writeJson(json);
    }

    public String showFences() {
        try {
            String name = this.getRequest().getParameter("name");
            SmapInfo smap = (SmapInfo)this.smapInfoService.selectByPrimaryKey(this.smapInfo.getId(), SmapInfo.class);
            BeanUtils.copyProperties(smap, this.getModel());
            FenceInfoExample example = new FenceInfoExample();
            example.createCriteria().andSmapIdEqualTo(this.smapInfo.getId());
            List fences = this.fenceInfoService.selectByExample(example);
            this.getRequest().setAttribute("fences", JSONArray.fromObject(fences));
            this.getRequest().setAttribute("smap", JSONObject.fromObject(smap));
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return "showFencesPage";
    }

    public void loadFences() {
        try {
            FenceInfoExample example = new FenceInfoExample();
            FenceInfoExampleBase.Criteria criteria = example.createCriteria();
            String smapId = this.getRequest().getParameter("smapId");
            if(StringUtils.isNotBlank(smapId)) {
                criteria.andSmapIdEqualTo(smapId);
            }

            String fenceId = this.getRequest().getParameter("fenceId");
            if(StringUtils.isNotBlank(fenceId)) {
                criteria.andIdEqualTo(fenceId);
            }

            List fences = this.fenceInfoService.selectByExample(example);
            this.writeJson(fences);
        } catch (Exception var6) {
            var6.printStackTrace();
            JSONArray jsonArray = new JSONArray();
            this.writeJson(jsonArray);
        }

    }

    public String monitor() {
        try {
            this.getRequest().setAttribute("config", this.readMonitorConfig());
            List list = this.regionInfoService.selectByExample(new RegionInfoExample());
            this.getRequest().setAttribute("regions", JSONArray.fromObject(list));
        } catch (Exception var2) {
            var2.printStackTrace();
        }

        File file = new File("1.txt");
        return file.exists()?"showMonitorPage":"showPanel";
    }

    public void loadPoints() {
        Object maps = new LinkedList();

        try {
            String smapId = this.getRequest().getParameter("smapId");
            String empId = this.getRequest().getParameter("empId");
            String fenceId = this.getRequest().getParameter("fenceId");
            String devId = this.getRequest().getParameter("devId");
            Map map = new HashMap();
            if(StringUtils.isNotBlank(smapId)) {
                map.put("smapId", smapId);
                map.put("limitStart", Integer.valueOf(0));
                map.put("rowsPerPage", Integer.valueOf(100000));
                maps = this.pointInfoService.selectBySmapId(map);
            } else if(StringUtils.isNotBlank(empId)) {
                map.put("empId", empId);
                map.put("limitStart", Integer.valueOf(0));
                map.put("rowsPerPage", Integer.valueOf(1));
                maps = this.pointInfoService.selectByEmpId(map);
            } else if(StringUtils.isNotBlank(fenceId)) {
                map.put("fenceId", fenceId);
                map.put("limitStart", Integer.valueOf(0));
                map.put("rowsPerPage", Integer.valueOf(100000));
                maps = this.pointInfoService.selectByApMac(map);
            } else if(StringUtils.isNotBlank(devId)) {
                String[] split = StringUtils.split(devId, "__");
                map.put("devId", split[0]);
                map.put("devMac", split[1]);
                map.put("limitStart", Integer.valueOf(0));
                map.put("rowsPerPage", Integer.valueOf(100000));
                maps = this.pointInfoService.selectByDeviceMac(map);
            }
        } catch (Exception var8) {
            var8.printStackTrace();
        }

        this.writeJson(maps);
    }

    public Map readMonitorConfig() {
        Map<String, Object> map = new HashMap();
        String realPath = this.getRequest().getRealPath("/") + "monitor.properties";

        try {
            if(!(new File(realPath)).exists()) {
                map.put("min", Integer.valueOf(40));
                map.put("max", Integer.valueOf(160));
            } else {
                Properties properties = new Properties();
                properties.load(new FileInputStream(realPath));
                String min = properties.getProperty("min", "40");
                String max = properties.getProperty("max", "160");
                map.put("min", min);
                map.put("max", max);
            }
        } catch (Exception var6) {
            LOG.error("设置失败！", var6, new String[0]);
        }

        return map;
    }

    public void setMonitorConfig() {
        PageJson json = new PageJson();

        try {
            Properties prop = new Properties();
            String realPath = this.getRequest().getRealPath("/") + "monitor.properties";
            OutputStream fos = new FileOutputStream(new File(realPath));
            prop.setProperty("min", this.getRequest().getParameter("min"));
            prop.setProperty("max", this.getRequest().getParameter("max"));
            prop.store(fos, "Update sdkserver.url,userName,password value");
            json.setReturnMsg("设置成功！");
            json.setReturnFlag(true);
        } catch (Exception var5) {
            LOG.error("设置失败！", var5, new String[0]);
            json.setReturnMsg("设置失败！");
            json.setReturnFlag(false);
        }

        this.writeJson(json);
    }

    public SmapInfo getModel() {
        return this.smapInfo;
    }
}
